package cn.llin.common.utils;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * Larry
 * 2021/10/29 08:41
 *
 * @Version 1.0
 */
public class RMBTool {

    /**
     * 元转分，确保price保留两位有效数字
     *
     * @return
     */
    public static int changeY2F(double price) {
        DecimalFormat df = new DecimalFormat("#.00");
        price = Double.valueOf(df.format(price));
        int money = (int) (price * 100);
        return money;
    }

    /**
     * 分转元，转换为bigDecimal在toString
     *
     * @return
     */
    public static String changeF2Y(int price) {
        return BigDecimal.valueOf(Long.valueOf(price)).divide(new BigDecimal(100)).toString();
    }

    public static String changeF2Y(String price) {
        int len = price.length();

        String y = "";
        if (len > 2) {
            String s1 = price.substring(0, len - 2);
            String s2 = price.substring(len - 2, len);
            y = s1 + "." + s2;
        } else if (len == 2) {
            y = "0." + price;
        } else {
            y = "0.0" + price;
        }
        return y;
    }
}
